use crate::common::models::enums::charset::*;
use crate::common::consts::comm_const::APP_CONF_PATH;
use crate::common::consts::auth_const;
use serde_derive::Deserialize;
use std::fs::File;
use std::io::Read;
use std::ops::Deref;
use std::borrow::Borrow;
use crate::common::consts::auth_const::{DEFAULT_USER_NAME, DEFAULT_PASSWORD};

/// desc: 全局配置懒加载
/// author: Graves
/// date: 2022-07-19 21:21:17
lazy_static! {
    static ref SERVER_CONF: ServerConf = init_server_conf();
}

/// desc  : 获取配置对象引用
/// author: Graves
/// date  : 2022-07-19 21:00:23
pub trait GetProperties {
    /// 获取服务策略配置
    fn get_strategy(&'static self) -> &'static String;
}

/// desc  : 获取配置对象引用实现
/// author: Graves
/// date  : 2022-07-19 21:00:23
impl GetProperties for ServerConf {
    /// 获取服务策略配置
    fn get_strategy(&'static self) -> &'static String {
        self.engine_strategy.as_ref().unwrap()
    }
}

/// desc  : 获取配置对象引用
/// author: Graves
/// date  : 2022-07-19 21:00:23
pub fn get_server_conf() -> &'static ServerConf {
    &SERVER_CONF
}

#[derive(Debug)]
#[derive(Deserialize)]
pub struct ServerConf {
    port: Option<u32>,
    default_path: Option<String>,
    connection_timeout: Option<u32>,
    charset: Option<String>,
    engine_strategy: Option<String>,
    default_user_name: Option<String>,
    default_password: Option<String>,
}

#[derive(Debug)]
#[derive(Deserialize)]
struct Conf {
    server_conf: Option<ServerConf>,
}

/// desc  : 服务端配置初始化
/// author: Graves
/// date  : 2022/7/8 15:00
fn init_server_conf() -> ServerConf {
    let file_name = APP_CONF_PATH;
    let mut file = match File::open(file_name) {
        Ok(f) => f,
        Err(e) => panic!("[Server Config Init Fail] no such file {} exception:{}", file_name, e)
    };
    let mut conf = String::new();
    match file.read_to_string(&mut conf) {
        Ok(s) => s,
        Err(e) => panic!("[Server Config Init Fail] Error Reading file: {}", e)
    };
    let conf: Conf = toml::from_str(&conf).unwrap();
    let mut server_conf = conf.server_conf.unwrap();
    assert!(!server_conf.charset.is_none(), "[Server Config Init Fail] 启动失败, 请设置服务字符集编码!!");
    println!("[Server Config Init] 初始化引擎加载策略: {:?}", server_conf.engine_strategy.as_deref().unwrap());
    let charset = server_conf.charset.clone().unwrap();
    Charset::valid_charset(charset);
    // 若未配置初始化账号密码, 则使用默认账号密码
    if server_conf.default_user_name.is_none() {
        println!("[Server Config Init] 用户账号为空, 请使用默认账号密码进行登录 {:?} / {:?}", DEFAULT_USER_NAME, DEFAULT_PASSWORD);
        server_conf.default_user_name = Option::Some(DEFAULT_USER_NAME.to_string());
        server_conf.default_password = Option::Some(DEFAULT_PASSWORD.to_string());
    }
    server_conf
}